package com.googlecode.maven.plugin.appassembler;

import freemarker.cache.TemplateLoader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

/**
 * FreeMarker template loader that uses Spring Frameworks resource names to
 * locate templates.
 */
public class ResourceTemplateLoader
        implements TemplateLoader
    {
    /**
     * Spring resource loader.
     */
    private final ResourceLoader resourceLoader = new DefaultResourceLoader();

    /**
     * {@inheritDoc}
     */
    public Object findTemplateSource(String name)
            throws IOException
        {
        Resource resource = resourceLoader.getResource(name);
        if (!resource.exists())
            {
            return null;
            }
        return resource;
        }

    /**
     * {@inheritDoc}
     */
    public long getLastModified(Object templateSource)
        {
        return -1;
        }

    /**
     * {@inheritDoc}
     */
    public Reader getReader(Object templateSource, String encoding)
            throws IOException
        {
        Resource resource = (Resource) templateSource;
        return new InputStreamReader(resource.getInputStream(), encoding);
        }

    /**
     * {@inheritDoc}
     */
    public void closeTemplateSource(Object templateSource)
            throws IOException
        {
        // do nothing
        }
    }
